import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import Form from './components/Form';

import * as api from '@/services/smartModeConfig';
import * as utils from '@/utils/utils';
import { PageContainer } from '@ant-design/pro-components';

const SmartModeConfigList: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.SmartModeConfig | undefined>(
    undefined,
  );

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {
    const result = await api.list(params, sorter, filter);
    return Promise.resolve(result);
  };

  const handleFormSubmit = async (record: API.SmartModeConfig) => {
    let result: API.Result;
    console.log({
      ...current,
      ...record,
    });
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();
    }
  };

  const handleRemove = async (id: string) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  let columns: ProColumns<API.SmartModeConfig>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      sorter: true,
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: '地区分组',
      align: 'center',
      width: 140,
      dataIndex: 'areaGroup',
      sorter: true,
    },
    {
      title: '国家地区',
      align: 'center',
      width: 140,
      dataIndex: 'contury',
      sorter: true,
    },
    {
      title: 'Code',
      align: 'center',
      width: 80,
      dataIndex: 'conturyCode',
      sorter: true,
    },
    // {
    //   title: 'IP配置',
    //   dataIndex: 'skipIpConfig',
    //   render: (_, record) => {
    //     return (
    //       <>
    //         <span>地址: {record.skipIpConfig?.url}</span>
    //         <br />
    //         <span>MD5: {record.skipIpConfig?.md5}</span>
    //       </>
    //     );
    //   },
    // },
    {
      title: '域名内容',
      dataIndex: 'skipDomainConfig',
      ellipsis: true,
      render: (_, record) => {
        return <>{record.skipDomainConfig?.content}</>;
      },
    },
    {
      title: '版本属性',
      width: 400,
      render: (_, record) => {
        return (
          <>
            {/* <span>地址: {record.skipIpConfig?.url}</span> */}
            <span>VER: {record.skipDomainConfig?.ver}</span>
            <br />
            <span>MD5: {record.skipDomainConfig?.md5}</span>
          </>
        );
      },
    },
    {
      title: 'Xray配置',
      width: 400,
      render: (_, record) => {
        return record.xrayConfig?.map((val) => {
          return (
          <div>
            <span>VER: {val?.ver}</span>
            <br />
            <span>MD5: {val?.md5}</span>
          </div>
        );
        });
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
    {
      title: '修改时间',
      align: 'center',
      width: 200,
      dataIndex: 'updateTime',
      sorter: true,
      renderText: (_, record) => {
        return utils.formatUtcToLocal(record.updateTime);
      },
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 140,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('smartmodeconfig_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('smartmodeconfig_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        cardProps={{ bodyStyle: { padding: 0 } }}
        search={false}
        style={{ border: 1 }}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        pagination={{
          defaultPageSize: 15,
          pageSizeOptions: ['15', '30', '60', '100'],
          hideOnSinglePage: true,
          // current: pageCurrent,
          // total: totalCount,
        }}
        toolBarRender={() => {
          if (hasRight('smartmodeconfig_create')) {
            return [
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ];
          }
          return [];
        }}
        columns={columns}
        request={loadData}
      />
      <Form
        visible={formVisible}
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default SmartModeConfigList;
